#!/usr/bin/python3
from ms5837 import MS5837
import time
import csv
import psutil
import sys
import os
import wiringpi

# 进程查询，防止多运行
def checkProcess(processName):
    # processName = os.path.basename(__file__)
    ps1=psutil.pids()
    curps=os.getpid()
    for pid in ps1:
        try:
            cmdline = psutil.Process(pid).cmdline()
        except psutil.NoSuchProcess:
            continue
        # print(cmdline)
        if processName in cmdline and pid != curps and pid != (curps - 1):
            print(f"{processName}:, This is the second process pid = {str(pid)}, so exit!")
            sys.exit(1)
    print(f"now runing {processName},current pid = "+str(curps))
    return

if __name__ == "__main__":
    wiringpi.wiringPiSetup()
    _fileName = sys.argv[1]
    checkProcess(_fileName)
    # 创建 MS5837 对象,指定 I2C 总线编号(默认为 1)
    sensor = MS5837()

    # 初始化传感器
    if not sensor.init():
        print("传感器初始化失败!")
        sys.exit(1)

    # 设置液体密度,默认为淡水(997 kg/m^3)
    # 如果测量海水,可以使用 sensor.setFluidDensity(1029)
    print("MS5837 connect")
    sensor.setFluidDensity(997)

    # 指定数据文件保存路径
    formatted_time = time.strftime('%Y%m%d%H%M%S',time.localtime())
    Datafolder = 'Data/DepthData/'
    if not os.path.exists(Datafolder):
            os.makedirs(Datafolder)
    data_file = Datafolder + f"ms5837_data_{formatted_time}.csv"

    # 创建数据文件并写入表头
    with open(data_file, 'a') as file:
        writer = csv.writer(file)
        writer.writerow(["Depth (m)", "Timestamp",'microtime'])

    # 设置读取数据的时间间隔(以秒为单位)
    read_interval = 20000 # 20ms

    # 获取脚本启动时的浮点时间(秒)
    start_time = wiringpi.micros()

    # 循环读取数据并写入文件3
    while True:
        loop_start_time = wiringpi.micros()
        try:
            # 读取传感器数据mode='w'
            if sensor.read():
                # 获取深度数据(单位:米)
                depth = sensor.depth()

                # 获取当前时间戳
                timestamp = time.time()# loop_start_time - start_time

                # 将时间戳和深度数据写入文件
                with open(data_file, mode='a') as file:
                    writer = csv.writer(file)
                    # writer.writerow([timestamp, depth])
                    writer.writerow([depth, timestamp,wiringpi.micros()])


                # print("时间戳: %s, 深度: %.2f m" % (timestamp, depth))
            else:
                print("传感器读取数据失败!")

            loop_end_time = wiringpi.micros()
            elapsed_time = loop_end_time - loop_start_time

            # 如果读取和写入数据的时间小于设定的时间间隔,则等待剩余时间
            if elapsed_time < read_interval:
                wiringpi.delayMicroseconds(read_interval - elapsed_time)

        except KeyboardInterrupt:
            print("程序已终止.")
            break